package ai.zixing.mashibing.new_class.class04;

import java.util.List;

public class Code05_AddTwoNumbers {
    public static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int value) {
            val = value;
        }
    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int len1 = listLength(l1);
        int len2 = listLength(l2);
        ListNode l = len1 >= len2 ? l1 : l2;
        ListNode s = len1 < len2 ? l1 : l2;

        ListNode curL = l;
        ListNode curS = s;
        // 维护最后一个节点的进位情况
        ListNode cur = curL;
        int carry = 0;
        int curNum = 0;
        // 处理短链表
        while (curS != null) {
            curNum = curL.val + curS.val + carry;
            curL.val = curNum % 10;
            carry = curNum / 10;
            cur = curL;
            curL = curL.next;
            curS = curS.next;
        }
        // 处理长链表，此时短链表相加完了
        while (curL != null) {
            curNum = curL.val + carry;
            curL.val = curNum % 10;
            carry = curNum / 10;
            cur = curL;
            curL = curL.next;
        }
        // 最后长链表有进位
        if (carry != 0) {
            cur.next = new ListNode(1);
        }
        return l;
    }


    // 求链表长度，找到长链表
    public static int listLength(ListNode head) {
        int len = 0;
        while (head != null) {
            len++;
            head = head.next;
        }
        return len;
    }
}
